﻿var dataBaseAgenda = new Date();
var permissao;

$(document).ready(function () {
    $(".nav li").removeClass("active");
    $(".nav li.agenda").addClass("active");
    $("#selectDentista").change(selecionarDentista);
    $("#selectCliente").change(selecionarCliente);
    //permissao = getPermissao();
    iniciarCalendario();
});

function getPermissao() {
    var ret;
    $.ajax({
        type: 'POST',
        url: 'Agenda.aspx/getPermissao',
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            ret = data.d;
        }
    });
    return ret;
}

function iniciarCalendario() {
    var $calendar = $('#agenda');

    $calendar.weekCalendar({
        buttons: false,
        timeslotsPerHour: 4,
        allowCalEventOverlap: true,
        overlapEventsSeparate: false,
        firstDayOfWeek: 1,
        businessHours: { start: 8, end: 21, limitDisplay: true },
        daysToShow: 6,
        height: function ($calendar) {
            return $("#agenda").height();
        },
        eventRender: function (calEvent, $event) {
            if (calEvent.end.getTime() < new Date().getTime()) {
                $event.css("backgroundColor", "#aaa");
                $event.find(".wc-time").css({
                    "backgroundColor": "#999",
                    "border": "1px solid #888"
                });
            }
        },
        draggable: function (calEvent, $event) {
            return calEvent.readOnly != true;
        },
        resizable: function (calEvent, $event) {
            return calEvent.readOnly != true;
        },
        eventNew: function (calEvent, $event) {
            if ($("#selectDentista").val() == -1) {
                alert("Selecione um dentista");
                $("#selectDentista").focus();
                $('#agenda').weekCalendar("removeUnsavedEvents");
                return;
            }

            var $dialogContent = $("#edicao_evento");
            resetForm($dialogContent);

            $("#botoesExtras").hide(0);
            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField = $dialogContent.find("select[name='end']").val(calEvent.end);

            calEvent.id = eventId;
            eventId++;

            globalCalEvent = calEvent;
            $dialogContent.modal('toggle');
            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
            $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
            setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
        },
        eventDrop: function (calEvent, $event) {
        },
        eventResize: function (calEvent, $event) {
        },
        eventClick: function (calEvent, $event) {
            if (calEvent.readOnly) {
                return;
            }

            var $dialogContent = $("#edicao_evento");
            resetForm($dialogContent);

            $("#botoesExtras").show(0);
            $(".modal-body select, .modal-body input, .modal-body textarea").attr("disabled", "disabled");

            $("#btnCancelar").show(0);

            if (calEvent.compareceu) {
                $("#btnCompareceu").addClass("disabled");
                $("#btnCancelar").hide(0);
            }

            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
            $dialogContent.find("#selectCliente").val(calEvent.idCliente);
            $dialogContent.find("#observacoes").val(calEvent.observacoes);

            globalCalEvent = calEvent;
            $dialogContent.modal('toggle');

            $("#btnSalvar").addClass("disabled");
            $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
            setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
        },
        eventMouseover: function (calEvent, $event) {
        },
        eventMouseout: function (calEvent, $event) {
        },
        noEvents: function () {
        },
        data: function (start, end, callback) {
            callback(getEventData());
        }
    });

    function resetForm($dialogContent) {
        $dialogContent.find(".modal-body input, .modal-body textarea, .modal-body select").val("");
        $("#selectProcedimento option").remove();
        $("#selectProcedimento").append($("<option value=\"-1\">Selecione o cliente</option>"));
    }

    function getEventData() {
        return {
            events: globalEvents
        };
    }

    function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {
        for (var i = 0; i < timeslotTimes.length; i++) {
            var startTime = timeslotTimes[i].start;
            var endTime = timeslotTimes[i].end;
            var startSelected = "";
            if (startTime.getTime() === calEvent.start.getTime()) {
                startSelected = "selected=\"selected\"";
            }
            var endSelected = "";
            if (endTime.getTime() === calEvent.end.getTime()) {
                endSelected = "selected=\"selected\"";
            }
            $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
            $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");
        }
        $endTimeOptions = $endTimeField.find("option");
        $startTimeField.trigger("change");
    }

    $endTimeField = $("select[name='end']");
    $endTimeOptions = $endTimeField.find("option");

    $("select[name='start']").change(function () {
        var startTime = $(this).find(":selected").val();
        var currentEndTime = $endTimeField.find("option:selected").val();
        $endTimeField.html(
                $endTimeOptions.filter(function () {
                    return startTime < $(this).val();
                })
                );

        var endTimeSelected = false;
        $endTimeField.find("option").each(function () {
            if ($(this).val() === currentEndTime) {
                $(this).attr("selected", "selected");
                endTimeSelected = true;
                return false;
            }
        });

        if (!endTimeSelected) {
            //automatically select an end date 2 slots away.
            $endTimeField.find("option:eq(1)").attr("selected", "selected");
        }
    });

    refreshEvents();
}

var globalEvents = [];
var globalCalEvent;
var eventId = 10;

function refreshEvents() {
    $.ajax({
        type: 'POST',
        url: 'Agenda.aspx/getAgendaDentista',
        data: "{idDentista: " + $("#selectDentista").val() + ", data: '" + dataBaseAgenda.getData() + "'}",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            globalEvents = data.d;
            if (data.d.length > 0)
                trataGlobalEvents();

            eventId = data.d.length + 1;

            $("#agenda").weekCalendar("refresh");
        }
    });
}

function trataGlobalEvents() {
    for (var i in globalEvents) {
        globalEvents[i].start = new Date(globalEvents[i].start);
        globalEvents[i].end = new Date(globalEvents[i].end);
    }
}

function modalEvent_Salvar() {
    if ($("#btnSalvar").hasClass("disabled"))
        return;

    $("#btnSalvar").button('loading');
    $(".modal-footer .btn").addClass("disabled");

    var $dialogContent = $("#edicao_evento");
    var startField = $dialogContent.find("select[name='start']");
    var endField = $dialogContent.find("select[name='end']");
    var clienteField = $dialogContent.find("#selectCliente");
    var procedimentoField = $("#selectProcedimento");
    var title = $("#selectCliente option:selected").text();
    var observacoesField = $dialogContent.find("#observacoes");

    globalCalEvent.start = new Date(startField.val());
    globalCalEvent.end = new Date(endField.val());
    globalCalEvent.title = title;
    globalCalEvent.idCliente = clienteField.val();
    globalCalEvent.idProcedimentoCliente = procedimentoField.val();
    globalCalEvent.observacoes = observacoesField.val();

    if (isNaN(parseInt(globalCalEvent.idCliente)) || parseInt(globalCalEvent.idCliente) <= 0) {
        alert("Você deve selecionar um cliente");
        return;
    }

    if (isNaN(parseInt(globalCalEvent.idProcedimentoCliente)) || parseInt(globalCalEvent.idProcedimentoCliente) <= 0) {
        alert("Você deve selecionar um procedimento");
        return;
    }

    $.ajax({
        type: 'POST',
        url: 'Agenda.aspx/salvarAgenda',
        data: "{idProcedimentoCliente: " + procedimentoField.val() + "," +
                "idDentista: " + $("#selectDentista").val() + "," +
                "dtInicial: '" + globalCalEvent.start.getDataHora() + "'," +
                "dtFinal: '" + globalCalEvent.end.getDataHora() + "'," +
                "observacoes: '" + globalCalEvent.observacoes + "'}",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            globalCalEvent.id_agenda = data.d;
            $('#agenda').weekCalendar("updateEvent", globalCalEvent);
            fecharCadastroAgenda();
        }
    });
}

function modalEvent_Fechar() {
    fecharCadastroAgenda();
}

function modalEvent_Cancelar() {
    $.ajax({
        type: 'POST',
        url: 'Agenda.aspx/cancelar',
        data: "{idAgenda: " + globalCalEvent.id_agenda + "}",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $('#agenda').weekCalendar("removeEvent", globalCalEvent.id);
            fecharCadastroAgenda();
        }
    });
}

function modalEvent_Comparecer() {
    if ($("#btnCompareceu").hasClass("disabled"))
        return;

    $.ajax({
        type: 'POST',
        url: 'Agenda.aspx/compareceu',
        data: "{idAgenda: " + globalCalEvent.id_agenda + "}",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            globalCalEvent.compareceu = true;
            $('#agenda').weekCalendar("updateEvent", globalCalEvent);
            fecharCadastroAgenda();
        }
    });
}

function fecharCadastroAgenda() {
    $("#botoesExtras").show(0);
    $('#agenda').weekCalendar("removeUnsavedEvents");
    $("#edicao_evento").modal('toggle');
    $(".modal-footer .btn").removeClass("disabled");
    $("#btnSalvar").button('reset');
    $(".modal-body select, .modal-body input, .modal-body textarea").removeAttr("disabled");
}

function selecionarDentista() {
    refreshEvents();
}

function selecionarCliente() {
    var idCliente = $("#selectCliente").val();

    $.ajax({
        type: 'POST',
        url: 'Agenda.aspx/getProcedimentosCliente',
        data: "{idCliente: " + idCliente + "}",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $("#selectProcedimento option").remove();
            if (data.d.length > 0) {
                for (var i = 0; i < data.d.length; i++)
                    $("#selectProcedimento").append($("<option value=\"" + data.d[i].id_procedimento_cliente + "\">" + data.d[i].nome_procedimento + "</option>"));
            } else {
                $("#selectProcedimento").append($("<option value=\"-1\">Nenhum procedimento cadastrado para o cliente</option>"));
            }
        }
    });

}

function selecionarProcedimento() {

}

function calendarioHoje() {
    dataBaseAgenda = new Date();
    $("#agenda").weekCalendar("today");
    refreshEvents();
}

function calendarioProximaSemana() {
    dataBaseAgenda.addSemana(1);
    $("#agenda").weekCalendar("nextWeek");
    refreshEvents();
}

function calendarioSemanaAnterior() {
    dataBaseAgenda.addSemana(-1);
    $("#agenda").weekCalendar("prevWeek");
    refreshEvents();
}

Date.prototype.addSemana = function (qtd) {
    var MILIS_IN_A_WEEK = 7 * 24 * 60 * 60000;
    this.setTime(this.getTime() + (qtd * MILIS_IN_A_WEEK));
}

Date.prototype.getData = function () {
    return this.getDate() + "/" + (this.getMonth() + 1) + "/" + this.getFullYear();
}

Date.prototype.getDataHora = function () {
    return this.getData() + " " + this.getHours() + ":" + this.getMinutes();
}